<template>
    <tableLayout :columns="columns" :operationShow="true" :get="getData" :selectItem="selectItem" :rules="rules"
        ref="layout" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template #button>
            <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
            <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
            <a-button type="primary" style="margin-left: 20px" @click='syncToDB' :disabled="selectedRowKeys.length !== 1">同步到数据库</a-button>
            <a-button type="primary" style="margin-left: 20px" @click="del" :disabled="selectedRowKeys.length !== 1"
                danger>删除</a-button>
        </template>

        <template #operationMore="item">
            <a @click="edit(null, item.value.record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="del(null, item.value.record.Id)">删除</a>
        </template>

        <template v-slot:custom="data">
            <a-input v-model:value="data.formData[data.key]" />
        </template>
    </tableLayout>



    <a-modal :title="formState.Id ? '编辑表单' : '新增表单'" v-model:visible="modal_visible" :confirm-loading="confirmLoading"
        @ok="modal_handleOk" width="1200px">
        <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
            layout="inline" class="comform">
            <a-form-item label="表描述" style="width: calc(50% - 20px);" class="form__item" name="TableComments">
                <a-input v-model:value="formState.TableComments" placeholder="表描述" />
            </a-form-item>
            <a-form-item label="表名称" style="width: calc(50% - 20px);" class="form__item" name="TableName">
                <a-input v-model:value="formState.TableName" placeholder="表名称" />
            </a-form-item>
            <a-form-item label="表编码" style="width: calc(50% - 20px);" class="form__item" name="TableCode">
                <a-input v-model:value="formState.TableCode" :readonly="true" placeholder="表单编码">
                    <template #suffix>
                        <a-tooltip title="复制表编码">
                            <CopyTwoTone style="color: rgba(0, 0, 0, 0.45)" @click="onCopyTableCode" />
                        </a-tooltip>
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item label="是否有效" style="width: calc(50% - 20px);" class="form__item" name="IsValid">
                <a-checkbox v-model:checked="formState.IsValid" />
            </a-form-item>

            <a-form-item label="备注" style="width: calc(100% - 20px);" class="form__item" name="Remark"
                :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
                <a-textarea v-model:value="formState.Remark" placeholder="备注" :rows="4" />
            </a-form-item>
        </a-form>
        <hr style="border-style: dashed;" />
        <a-button type="primary" style="margin-top: 10px;margin-left:10px" size="small" @click="addColumn">
            <template #icon>
                <PlusOutlined />
            </template>
            创建字段</a-button>
        <a-table :columns="table_columns" size="small" rowKey="Key" :data-source="tableDataSource" :pagination="false"
            :scroll="{ y: 320 }" style="margin-top: 10px;" bordered>
            <template 
                v-for="col in ['Columns', 'Name', 'DataLength', 'DataType', 'IsValid', 'IsPrimaryKey', 'IsAllowNull', 'IsUniqueKey']"
                #[col]="{ text, record }" :key="col">
                <div>
                    <a-select v-model:value="record[col]" v-if="col == 'DataType'" style="width: 90px;" :disabled="record.Columns === 'BusinessKey'">
                        <a-select-option :value="1">字符串</a-select-option>
                        <a-select-option :value="2">整数</a-select-option>
                        <a-select-option :value="3">小数</a-select-option>
                        <a-select-option :value="4">日期时间</a-select-option>
                        <a-select-option :value="5">布尔类型</a-select-option>
                        <a-select-option :value="6">二进制</a-select-option>
                    </a-select>

                    <a-checkbox v-model:checked="record[col]"
                        v-else-if="['IsValid', 'IsPrimaryKey', 'IsAllowNull', 'IsUniqueKey'].includes(col)" :disabled="record.Columns === 'BusinessKey'"></a-checkbox>

                    <a-input-number v-else-if="col == 'DataLength'" v-model:value="record[col]"
                        style="margin: -5px 0" :disabled="record.Columns === 'BusinessKey'"/>

                    <a-input v-else v-model:value="record[col]" style="margin: -5px 0" :disabled="record.Columns === 'BusinessKey'"/>

                </div>
            </template>
            <template #operation="{ record }">
                <div class="editable-row-operations">

                    <span :class="{ 'disabled': record.Columns === 'BusinessKey' }">
                        <a @click="moveUp(record)">上移</a>
                    </span>
                    <span :class="{ 'disabled': record.Columns === 'BusinessKey' }">
                        <a @click="moveDown(record)">下移</a>
                    </span>
                    <span :class="{ 'disabled': record.Columns === 'BusinessKey' }">
                        <Confirm title="删除不能恢复，确认要删除?" @confirm="onDeleteColumn(record)">
                            <template #button>
                                <a>删除</a>
                            </template>
                        </Confirm>
                    </span>
                </div>
            </template>
        </a-table>
    </a-modal>

</template>

<script lang="ts" setup>
import { notification, message } from 'ant-design-vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { getData, deleteDataSource, saveOrUpdateDataSource,getColumnData,syncDB } from '@/api/datasources/datasource';
import { ref, UnwrapRef, reactive, nextTick, h } from 'vue';
import { CopyTwoTone, PlusOutlined } from '@ant-design/icons-vue';
import { DataSourceTableInput } from '@/types/api/datasources/datasource';
import { CustomIdPrefix } from '@/components/id/idGenerater';
import Confirm from '@/components/controls/confirm.vue';

const layout = ref();
const modal_visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref()

//表单对象
const formState: UnwrapRef<DataSourceTableInput> = reactive({
    Id: '',
    TableName: '',
    TableCode: '',
    TableComments: '',
    IsValid: true,
    Remark: '',
    DataSourceColumnInputs: []
});

//列表
const columns = [
    { title: '表名称', dataIndex: 'TableName' },
    { title: '表编码', dataIndex: 'TableCode' },
    { title: '表描述', dataIndex: 'TableComments' },
    {
        title: '是否有效', dataIndex: 'IsValid', customRender: function ({ text }): VNode {
            return h('div', {
                style: {
                    color: 'red'
                }
            }, text == 1 ? '有效' : '无效');
        }
    },
    { title: '创建时间', dataIndex: 'CreateTime' }
]

const table_columns = [
    { title: '字段', dataIndex: 'Columns', slots: { customRender: 'Columns' } },
    { title: '字段名称', dataIndex: 'Name', slots: { customRender: 'Name' } },
    { title: '数据长度', dataIndex: 'DataLength', width: 100, slots: { customRender: 'DataLength' } },
    { title: '数据类型', dataIndex: 'DataType', width: 100, slots: { customRender: 'DataType' } },
    { title: '有效', dataIndex: 'IsValid', width: 60, slots: { customRender: 'IsValid' } },
    { title: '可空', dataIndex: 'IsAllowNull', width: 60, slots: { customRender: 'IsAllowNull' } },
    { title: '主键', dataIndex: 'IsPrimaryKey', width: 60, slots: { customRender: 'IsPrimaryKey' } },
    { title: '唯一键', dataIndex: 'IsUniqueKey', width: 70, slots: { customRender: 'IsUniqueKey' } },
    { title: '序号', dataIndex: 'SortNum', width: 60},
    { title: '操作', dataIndex: 'operation', width: 180, slots: { customRender: 'operation' } }

]

const tableDataSource = ref([]);

// 筛选
const selectItem = ref([
    { title: '表名称', key: 'TableName', type: 'input', itemWidth: '290px' },
    { title: '表编码', key: 'TableCode', type: 'input', itemWidth: '290px' },
    { title: '表描述', key: 'TableComments', type: 'input', itemWidth: '290px' }
])

// 规则
const rules = {
    TableName: [{ required: true, message: '请输入表名', trigger: 'change' }],
    TableCode: [{ required: true, message: '请输入表编码', trigger: 'change' }],
    TableComments: [{ required: true, message: '请输入表描述', trigger: 'change' }]
}

//新增
const add = () => {
    modal_visible.value = true;
    let tableCode = CustomIdPrefix("Table");
    Object.keys(formState).forEach(key => {
        if (key === 'TableCode') {
            formState[key] = tableCode;
        } else {
            formState[key] = ''; // 清空其他字段
        }
    });
    tableDataSource.value=[];
    tableDataSource.value.push({ Columns: 'BusinessKey', Name: '业务主键', DataLength: 0, DataType: 1, SortNum: 1, IsValid: true, IsAllowNull: false, IsPrimaryKey: false, IsUniqueKey: true });
}

const edit = (event: any, item: any) => {
    let selectItem = item;
    if (!selectItem) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectItem = selectedRows.value[0];
    }
    modal_visible.value = true;
    Object.assign(formState, selectItem);
    getColumnData({ dataSourceTableId: selectItem.Id }).then(e => {
        var data = e.data.Data||[]; 
        // if(data.length==0){
        //     //自动加一个BusinessKey字段
        //     data.push({ Columns: 'BusinessKey', Name: '业务主键', DataLength: 0, DataType: 1, SortNum: 1, IsValid: true, IsAllowNull: false, IsPrimaryKey: false, IsUniqueKey: true });
        // }
        //给data设置Key
        data.forEach((item:any, index:number) => {
            let key = CustomIdPrefix('TableColumnKey');
            item.Key = key;
        });
        //data排序
        data.sort((a:any, b:any) => {
            return a.SortNum - b.SortNum;
        });
        tableDataSource.value = data;
    }).catch(err => {
        console.log(err);
        message.error(err.message || "获取字段数据失败!")
    })
}

//删除一条记录
const del = (event: any, id: any) => {
    let selectId = id;
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        }
        selectId = selectedRows.value[0].Id;
    }

    deleteDataSource({ Id: selectId }).then(() => {
        message.success("删除成功!");
        layout.value.getData();
    }).catch(err => {
        message.error(err.message || "删除失败!")
        confirmLoading.value = false;
    })
}

//复制表单编码
const onCopyTableCode = async (event: any) => {
    try {
        await navigator.clipboard.writeText(formState.TableCode);
        message.success('复制成功！');
    } catch (err) {
        console.error('复制失败', err);
        message.error('复制失败，请手动复制');
    }
}

// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const singleSelection = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
    selectedRowKeys.value = keys;
    selectedRows.value = rows;
    singleSelection.value = rows[0];
}

const modal_handleOk = () => {
    formRef.value.validate().then(() => {
        confirmLoading.value = true;
        formState.DataSourceColumnInputs = tableDataSource.value;
        saveOrUpdateDataSource(formState).then(e => {
            message.success("操作成功！");
            confirmLoading.value = false;
            modal_visible.value = false;
            layout.value.getData();
        }).catch(err => {
            message.error(err.message || "操作失败!")
            confirmLoading.value = false;
        })
    }).catch(() => {
        message.error('请检查必填项是否全部填写!');
    })
}

const addColumn = () => {
    let key = CustomIdPrefix('TableColumnKey');
    let sortNum = tableDataSource.value.length + 1;
    tableDataSource.value.push({ Key: key, Columns: '', Name: '', DataLength: 0, SortNum: sortNum, IsValid: true, IsAllowNull: true, IsPrimaryKey: false, IsUniqueKey: false });
}
//删除字段
const onDeleteColumn = (record: any) => {
    let index = tableDataSource.value.findIndex(e => e.Key == record.Key);
    if (index >= 0) {
        tableDataSource.value.splice(index, 1);
     }
     //后面的重新排序
     for (let i = index; i < tableDataSource.value.length; i++) {
        tableDataSource.value[i].SortNum = tableDataSource.value[i].SortNum - 1; 
     }
}

const onCancelDeleteColumn = () => {
    alert()
}

//上移
const moveUp = (record: any) => {
    let index = tableDataSource.value.findIndex(e => e.Key == record.Key);
    if (index > 0) {
        let temp = tableDataSource.value[index];
        let tempSortNum = temp.SortNum;
        tableDataSource.value[index] = tableDataSource.value[index - 1];
        tableDataSource.value[index - 1] = temp;
        tableDataSource.value[index - 1].SortNum = tableDataSource.value[index].SortNum;
        tableDataSource.value[index].SortNum = tempSortNum;
    }
}

//下移
const moveDown = (record: any) => {
    let index = tableDataSource.value.findIndex(e => e.Key == record.Key);
    if (index < tableDataSource.value.length - 1) {
        let temp = tableDataSource.value[index];
        let tempSortNum = temp.SortNum;
        tableDataSource.value[index] = tableDataSource.value[index + 1];
        tableDataSource.value[index + 1] = temp;
        tableDataSource.value[index + 1].SortNum = tableDataSource.value[index].SortNum;
        tableDataSource.value[index].SortNum = tempSortNum;
    }
}

//同步到数据库
const syncToDB = (event: any, id: any) => {
    let selectId = id;  
    if (!selectId) {
        if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
            message.warning('请先选择一条数据!');
            return;
        } 
        selectId = selectedRows.value[0].Id;
    } 
    syncDB({ dataSourceTableId: selectId }).then(e => {
        message.success("同步成功!");
    }).catch(err => {
        message.error(err.message || "同步失败!")
    });
}

const labelCol = { span: 6 };
const wrapperCol = { span: 18 };
</script>

<style lang="scss" scoped>
.editable-row-operations {
    a {
        margin-right: 8px;
    }

    .disabled {
        a {
            color: #ccc;
            cursor: not-allowed;
        }
    }
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;

    }


    .ant-modal-body {
        flex: 1;
    }
}

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1 !important;
            flex-shrink: 0;
        }
    }
}
</style>
<style lang="scss">
.editable-row-operations a {
    margin-right: 8px;
}

.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;

    }



    .ant-modal-body {
        flex: 1;
    }
}

.comform {
    & .form__item {
        margin-bottom: 16px;

        & .ant-form-item-label {
            flex-grow: 1;
            flex-shrink: 0;
        }
    }
}
</style>